<template>
    <div>
        <el-page-header @back="goBack" :content="pageTitle"></el-page-header>
        <div class="common_line"></div>
        <el-form ref="addForm" :model="addForm" :rules="rules" label-width="auto" style="margin-top: 20px;width: 85%;">
            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">基本信息</div>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="客户名称:" prop="name">
                        <el-input style="width: 240px" v-model="addForm.name" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="分类:" prop="category">
                        <div style="display: flex;align-items: center;gap: 20px;">
                            <el-select style="width: 240px;" v-model="addForm.category" placeholder="请选择" clearable>
                                <el-option v-for="item in cateLists" :key="'cate_'+item.id" 
                                    :label="item.name" :value="item.id"></el-option>
                            </el-select>
                            <span @click="showAddCateAlert=true" style="cursor: pointer;font-size: 13px;color: #0099ff;">新增分类</span>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系人:">
                        <el-input style="width: 240px" v-model="addForm.corp_contact" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话:">
                        <el-input style="width: 240px" v-model="addForm.phone" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="价格等级:" prop="price_level">
                        <div style="display: flex;align-items: center;gap: 20px;">
                            <el-select style="width: 240px;" v-model="addForm.price_level" placeholder="请选择" clearable>
                                <el-option v-for="item in priceLevels" :key="'level_'+item.id" 
                                    :label="item.price_name" :value="item.id"></el-option>
                            </el-select>
                            <span @click="showAddLevelAlert=true" style="cursor: pointer;font-size: 13px;color: #0099ff;">新增</span>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="期初欠款:">
                        <el-input v-if="!customerId" style="width: 240px" @blur="moneyBlur" v-model="addForm.initial_money" placeholder="请输入" maxlength="50" clearable></el-input>
                        <span v-else>{{ addForm.initial_money }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="应收款:">
                        <span>{{ addForm.current_money }}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系地址:">
                        <el-input style="width: 240px" v-model="addForm.address" placeholder="请输入" maxlength="100" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">收货地址</div>
            <el-row>
                <div class="address">
                    <div v-for="item in addForm.address_data" :key="'addr_'+item.index" class="item">
                        <div class="base">
                            <div class="info">
                                <span style="width: 56px;;text-align: right;">收货人</span>
                                <el-input style="width: 200px" v-model="item.receiver_name" placeholder="请输入" maxlength="20" clearable></el-input>
                            </div>
                            <div class="info">
                                <span>收货人电话</span>
                                <el-input style="width: 200px" v-model="item.receiver_phone" placeholder="请输入" maxlength="20" clearable></el-input>
                            </div>
                        </div>
                        <div class="addr">
                            <div class="left">
                                <div>
                                    <span style="width: 60px;margin-right: 10px;">收货地址</span>
                                    <el-cascader
                                        v-model="item.selectCity"
                                        :options="cityOptions"
                                        :props="{ value: 'code', label: 'name' }"
                                        @change='itemChanged($event, item)'
                                        style="width: 280px;"
                                        clearable>
                                    </el-cascader>
                                </div>
                                <el-input style="width: 280px;margin-left: 70px;" v-model="item.detail" 
                                    placeholder="请输入详细地址" maxlength="100" clearable></el-input>
                            </div>
                            <div class="btns">
                                <span v-if="!item.is_default" class="set_default" @click="setDefault(item)">设为默认</span>
                                <span v-if="!item.is_default" >|</span>
                                <span v-if="addForm.address_data.length>1" class="remove" @click="removeAddress(item)">删除</span>
                            </div>
                        </div>
                        <p class="default" v-if="item.is_default">默认</p>
                    </div>
                    <el-button class="btn_primary_color add_btn" icon="el-icon-plus" size="small"
                        @click="addAddress" >新增收货地址</el-button>
                </div>
            </el-row>

            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">财务信息</div>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="开户银行:">
                        <el-input style="width: 240px" v-model="addForm.bank_name" placeholder="请输入" maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="银行账号:">
                        <el-input style="width: 240px" v-model="addForm.bank_account" placeholder="请输入" maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="客户税号:">
                        <el-input style="width: 240px" v-model="addForm.tax_id" placeholder="请输入" maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
             
            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;">其他信息</div>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="微信:">
                        <el-input style="width: 240px" v-model="addForm.wechat" placeholder="请输入" maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="邮箱:">
                        <el-input style="width: 240px" v-model="addForm.email" placeholder="请输入" maxlength="50" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="20">
                    <el-form-item label="备注:">
                        <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" v-model="addForm.remark" placeholder="请输入" clearable />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        
        <bottom-btns
            Width="70%"
            MarginTop="30px"
            :buttons="buttonList"
            @superBtnClick="handleButtonClick"
        ></bottom-btns>

        <el-dialog
            title="新增客户分类"
            :visible.sync="showAddCateAlert"
            width="30%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="cateInfo" label-width="auto" ref="cateForm" :rules="cateRules">
                    <el-form-item label="分类名称:" prop="name">
                        <el-input style="width: 240px;" maxlength="100" v-model="cateInfo.name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showAddCateAlert=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addCustomerCategory">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="新增价格等级"
            :visible.sync="showAddLevelAlert"
            width="30%"
            :close-on-click-modal="false"
            append-to-body
            center>
            <div style="padding-left: 20px;">
                <el-form :model="levelForm" label-width="auto" ref="levelForm" :rules="levelRules">
                    <el-form-item label="价格等级名称：" prop="price_name">
                        <el-input style="width: 240px;" maxlength="100" v-model="levelForm.price_name" placeholder="请输入" clearable />
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="showAddLevelAlert=false">取 消</el-button>
                <el-button size="small" class="btn_primary_color" @click="addPriceLevelCommit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getCustomerCates, infoCustomer, addCustomer, editCustomer, addCustomerCate } from "@/api/cooperate";
import { getPriceLevel, addPriceLevel } from '@/api/product';
import bottomBtns from "@/components/bottomBtns";
import { cityCodes } from "@/utils/city";

export default {
    name: 'customerEdit',
    components: {
        bottomBtns
    },
    data() {
        return {
            showAddCateAlert: false,
            backShouldRefresh: false,  //返回是否刷新分类
            showAddLevelAlert: false,
            customerId: '',
            pageTitle: '',
            addForm: {
				corp: '',
                name: '',
                phone: '',
                category: '', 
                current_money: 0,
                initial_money: 0,
                email: '',
                wechat: '',
                address: '',
                corp_contact: '',
                address_data: [{
                    index: 0,
                    is_default: 1,
                    receiver_name: '',
                    receiver_phone: '',
                    province_code: '',
                    city_code: '',
                    area_code: '',
                    province_name: '',
                    city_name: '',
                    area_name: '',
                    detail: ''
                }],
                tax_id: '',
                bank_account: '',
                bank_name: '',
                price_level: '',
                remark: ''
            },
            rules:{
                name: [
                    { required: true, message: "请输入客户名称", trigger: "blur" },
                ],
                category: [
                    { required: true, message: "请选择客户分类", trigger: "change" },
                ],
            },
            cateInfo: {
                name: ''
            },
            cateRules:{
                name: [
                    { required: true, message: "请输入分类名称", trigger: "blur" },
                ],
            },
            levelForm: {
                price_name: ''
            },
            levelRules: {
                price_name: [
                    { required: true, message: "请输入价格等级名称", trigger: "blur" },
                ],
            },
            priceLevels: [],
            cateLists: [],
            buttonList: [
                { name: '保存', type: 'commit', id:'1' },
                { name: '取消', type: 'cancel', id:'2' }
            ],
            cityOptions: cityCodes,
            hashTable: new Map() // 哈希表存储编码到路径的映射
        }
    },
    props: {
        corpId: {
            type: Number
        },
        editId: {
            type: Number
        }
    },
    mounted() {
        this.addForm.corp = this.corpId
        this.customerId = this.editId
        if (this.customerId) {
            this.pageTitle = '编辑客户'
            this.getCustomerInfo()
        }else{
            this.pageTitle = '新增客户'
        }
        this.getCategorys()
        this.getPriceLevels()
        this.buildHashTable();
    },
    methods: {
        goBack() {
            this.$emit('hidden', {isRefresh: this.backShouldRefresh})
        },
        buildHashTable() {
            const traverse = (node, parentPath = []) => {
                const currentPath = [...parentPath, node.name];
                this.hashTable.set(node.code, {
                    name: node.name,
                    path: currentPath.join('&')
                });

                if (node.children) {
                    node.children.forEach(child => traverse(child, currentPath));
                }
            };

            this.cityOptions.forEach(root => traverse(root));
        },
        moneyBlur(val) {
            let value = val.target.value
            value = value.replace(/^(?!-)([^-\d.])/g, ''); // 只允许负号、数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            this.addForm.initial_money = value ? parseFloat(value) : 0
            this.addForm.current_money = this.addForm.initial_money
        },
        // 获取客户分类
        getCategorys() {
            getCustomerCates({
                corp: this.addForm.corp,
                page: 1,
                num: 999
            }).then(res => {
                this.cateLists = res.data.data.category_list
            })
        },
        // 价格等级
        getPriceLevels() {
            getPriceLevel({corp: this.addForm.corp}).then(res => {
                this.priceLevels = res.data.data.level_list
            })
        },
        addCustomerCategory() {
            var that = this
            that.$refs['cateForm'].validate(valid => {
                if(!valid) return
                
                addCustomerCate({
                    corp: that.addForm.corp,
                    name: that.cateInfo.name
                }).then(res => {
                    if (res.code == 200){
                        that.cateInfo.name = ''
                        that.getCategorys()
                        that.showAddCateAlert = false
                        that.backShouldRefresh = true
                        that.$message({
                            message: '新增成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        addPriceLevelCommit() {
            var that = this
            that.$refs['levelForm'].validate(valid => {
                if(!valid) return
                
                addPriceLevel({
                    corp: that.addForm.corp,
                    price_name: that.levelForm.price_name
                }).then(res => {
                    if (res.code == 200){
                        that.levelForm.price_name = ''
                        that.getPriceLevels()
                        that.showAddLevelAlert = false
                        that.backShouldRefresh = true
                        that.$message({
                            message: '新增成功',
                            type: 'success'
                        })
                    }
                })
            })
        },
        // 获取客户信息
        getCustomerInfo() {
            infoCustomer(this.customerId, {corp: this.addForm.corp}).then(res => {
                let info = res.data.data
                if (info.address_data_show && info.address_data_show.length){
                    // 1. 排序：将 is_default === 1 的项排在首位
                    let sortedArray = [...info.address_data_show].sort((a, b) => {
                    if (a.is_default === b.is_default) return a.index - b.index; // 保持原始顺序
                        return b.is_default - a.is_default; // 降序排列，1 在前
                    });

                    info.address_data = sortedArray.filter((item, index) => {
                        item.index = index
                        if (item.province_code){
                            item.selectCity = [item.province_code, item.city_code, item.area_code]
                        }
                        return item
                    })
                }else {
                    info.address_data = []
                }
                this.addForm = info
            })
        },
        itemChanged(val, item) {
            if (val && val.length===3){
                this.addForm.address_data.forEach(_item => {
                    if (_item.index === item.index) {
                        let path = this.hashTable.get(val[2]).path
                        let names = path.split('&')

                        _item.province_code = val[0]
                        _item.city_code = val[1]
                        _item.area_code = val[2]
                        _item.province_name = names[0]
                        _item.city_name = names[1]
                        _item.area_name = names[2]
                    }
                })
            }
        },
        addAddress() {
            this.addForm.address_data.push({
                index: this.addForm.address_data.length,
                is_default: 0,
                receiver_name: '',
                receiver_phone: '',
                province_code: '',
                city_code: '',
                area_code: '',
                province_name: '',
                city_name: '',
                area_name: '',
                detail: ''
            })
        },
        removeAddress(item) {
            let res = this.addForm.address_data.filter(_item => _item.index != item.index)
            let findDefault = res.find(_item => _item.is_default)
            this.addForm.address_data = res.filter((_item, _index) => {
                _item.index = _index
                if (!findDefault && _index===0){
                    _item.is_default = 1
                }
                return _item
            })
        },
        setDefault(item) {
            let res = this.addForm.address_data.filter(_item => {
                _item.is_default = false
                if (_item.index === item.index){
                    _item.is_default = true
                }
                return _item
            })

            // 排序：将 is_default === 1 的项排在首位
            this.addForm.address_data = [...res].sort((a, b) => {
                if (a.is_default === b.is_default) return a.index - b.index; // 保持原始顺序
                return b.is_default - a.is_default; // 降序排列，1 在前
            });
        },
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存
                    this.commit()
                    break;
                case '2':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        commit() {
            var that = this
            that.$refs['addForm'].validate(valid => {
                if(!valid) return

                let temp = null
                if (that.customerId) {
                    temp = editCustomer(that.customerId, that.addForm)
                }else{
                    temp = addCustomer(that.addForm)
                }
                temp.then(res => {
                    if (res.code == 200){
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        that.$emit('success')
                    }
                })
            })
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .address {
        width: 800px;
        .item {
            width: 100%;
            position: relative;
            padding: 14px 22px;
            margin: 0 0 10px 70px;
            border: 1px solid #e8e8e8;
            background: #fafafa;
            font-size: 14px;
            color: #333;
            .base {
                display: flex;
                align-items: center;
                width: 100%;
                gap: 50px;
                .info {
                    display: inline-flex;
                    align-items: center;
                    gap: 15px;
                }
            }
            .addr {
                display: flex;
                align-items: center;
                width: 100%;
                justify-content: space-between;
                margin-top: 20px;
                .left {
                    display: flex;
                    align-items: center;
                    flex-direction: column;
                    gap: 10px;
                }
                .btns {
                    display: flex;
                    align-items: center;
                    gap: 15px;
                    font-size: 14px;
                    .set_default {
                        cursor: pointer;
                    }
                    .remove {
                        color: red;
                        cursor: pointer;
                    }
                }
            }
            .default {
                position: absolute;
                top: 0;
                right: 0;
                min-width: 64px;
                width: 64px !important;
                height: 22px;
                border-radius: 0 0 0 4px;
                background: @blue;
                color: #fff;
                text-align: center;
                line-height: 22px;
                font-size: 13px;
            }
        }
        .add_btn {
            margin: 10px 0 0 70px;
        }
    }
</style>